﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MediaPlayerControlLibrary;

namespace MediaPlayerSatVer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private double _currentVolume;

        // <- Tabs Globals
        private string[] titles = new string[4];
        private TextBlock cur_tab;
        private int cur_btn_index;
        // Tabs Globals ->

        public MainWindow()
        {
            InitializeComponent();

            // <- Tabs initialisation
            titles[0] = "Мельница";
            titles[1] = "Сборка";
            titles[2] = "Всё подряд";
            titles[3] = "Последний";
            cur_tab = tab1;
            cur_btn_index = 0;
            // Tabs initialisation ->

            playlistMenu.MouseLeave += PlayListMenuLeaveHandler;
        }

        protected void PlayListMenuLeaveHandler(Object sender, MouseEventArgs e)
        {
            playlistMenu.IsExpanded = false;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            volumeControl.Value = 80;
            _currentVolume = volumeControl.Value;

            StartMarquee(Marquee.Text); // Запускаем бегущую строку после загрузки окна. 
            // Если запустить в конструкторе формы, будут неправильно вычислены размеры

            // заполнение плейлиста тастовыми данными
            for (int i = 0; i < 20; i++)
            {
                var item = new SongInfo
                {

                    Number = i,
                    Title = "Песня номер № " + i.ToString(),
                    Time = "9:59:59",
                    PlayImage = new Image(),
                    ToolTip = "Это Песня номер № " + i.ToString()
                };
                playList.Items.Add(item);
            }

            AllSongsLenght.Content = "01:02:03";
        }

        /// <summary>
        /// Начать анимацию бегущей строки с заданным текстом
        /// </summary>
        /// <param name="text">Текст в бегущей строке</param>
        private void StartMarquee(string text)
        {
            Marquee.Text = text;

            FormattedText formattedText = new FormattedText(
                text,
                CultureInfo.GetCultureInfo("en-us"),
                Marquee.FlowDirection,
                new Typeface(
                    Marquee.FontFamily,
                    Marquee.FontStyle,
                    Marquee.FontWeight,
                    Marquee.FontStretch),
                Marquee.FontSize,
                Brushes.Black);

            Geometry geometry = formattedText.BuildHighlightGeometry(new System.Windows.Point(0, 0));

            double textLength = geometry.Bounds.Width;

            FrameworkElement Parent = ((Marquee.Parent as FrameworkElement).Parent as FrameworkElement);

            if (textLength > Parent.ActualWidth && Parent.ActualWidth != 0)
                MarqueeDA.To = -(textLength - Parent.ActualWidth) - 30;
            else
                MarqueeDA.To = 0;

            MarqueeDA.From = 0;

            MarqueeSB.Begin();
        }
		
        private void MinimizeButton_MouseUp(object sender, MouseButtonEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void CloseButton_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

        private void volumeButton_Click(object sender, RoutedEventArgs e)
        {
            if (volume_on.IsVisible)
            {
                volume_on.Visibility = Visibility.Hidden;
                volume_off.Visibility = Visibility.Visible;

                _currentVolume = Math.Round(volumeControl.Value);
                volumeControl.Value = 0;
            }
            else
            {
                volume_off.Visibility = Visibility.Hidden;
                volume_on.Visibility = Visibility.Visible;

                volumeControl.Value = _currentVolume;
            }
        }

        private void volumeControl_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            var value = Math.Round((sender as VolumeControl).Value);
            volumeControl.ToolTip = value;
            volumeLabel.Content = value;
        }

        
        //Обработчик нажатия первой кнопки
        private void B1_Click(object sender, RoutedEventArgs e)
        {
            //Изменяется прозрачность кнопки в соответствии с предыдущим состоянием
            if (this.B1.Opacity == 1)
            {
                this.B1.Opacity = 0.6;
            }
            else
            {
                this.B1.Opacity = 1;
            }
        }
        //Обработчик нажатия второй кнопки
        private void B2_Click(object sender, RoutedEventArgs e)
        {
            //Изменяется прозрачность кнопки в соответствии с предыдущим состоянием
            if (this.B2.Opacity == 1)
            {
                this.B2.Opacity = 0.6;
            }
            else
            {
                this.B2.Opacity = 1;
            }
        }
        //Обработчик нажатия третьей кнопки
        private void B3_Click(object sender, RoutedEventArgs e)
        {
            //Изменяется прозрачность кнопки в соответствии с предыдущим состоянием
            if (this.B3.Opacity == 1)
            {
                this.B3.Opacity = 0.6;
            }
            else
            {
                this.B3.Opacity = 1;
            }
        }

        private void b_play_Down(object sender, MouseButtonEventArgs e)
        {
			e.Handled = true;
            b_play.Visibility = System.Windows.Visibility.Hidden;
            b_play_over.Visibility = System.Windows.Visibility.Hidden;
            b_play_click.Visibility = System.Windows.Visibility.Visible;
            b_pause_over.Visibility = System.Windows.Visibility.Hidden;
        }
        private void b_play_Click(object sender, MouseButtonEventArgs e)
        {
            b_play.Visibility = System.Windows.Visibility.Hidden;
            b_play_over.Visibility = System.Windows.Visibility.Hidden;
            b_play_click.Visibility = System.Windows.Visibility.Hidden;
            b_pause.Visibility = System.Windows.Visibility.Visible;
        }
        private void b_pause_Down(object sender, MouseButtonEventArgs e)
        {
			e.Handled = true;
            b_pause.Visibility = System.Windows.Visibility.Hidden;
            b_pause_over.Visibility = System.Windows.Visibility.Hidden;
            b_pause_click.Visibility = System.Windows.Visibility.Visible;
        }
        private void b_pause_Click(object sender, MouseButtonEventArgs e)
        {
            b_pause_click.Visibility = System.Windows.Visibility.Hidden;
            b_play_over.Visibility = System.Windows.Visibility.Hidden;
            b_play.Visibility = System.Windows.Visibility.Visible;
            b_pause_over.Visibility = System.Windows.Visibility.Hidden;
        }
        private void b_last_track_Down(object sender, MouseButtonEventArgs e)
        {
			e.Handled = true;
            b_last_track.Visibility = System.Windows.Visibility.Hidden;
            b_last_track_over.Visibility = System.Windows.Visibility.Hidden;
            b_last_track_click.Visibility = System.Windows.Visibility.Visible;
        }
        private void b_last_track_Down1(object sender, MouseButtonEventArgs e)
        {
            b_last_track.Visibility = System.Windows.Visibility.Hidden;
            b_last_track_over.Visibility = System.Windows.Visibility.Hidden;
            b_last_track_click.Visibility = System.Windows.Visibility.Visible;
        }
        private void b_last_track_Click(object sender, MouseButtonEventArgs e)
        {
            b_last_track.Visibility = System.Windows.Visibility.Visible;
            b_last_track_over.Visibility = System.Windows.Visibility.Hidden;
            b_last_track_click.Visibility = System.Windows.Visibility.Hidden;
        }
        private void b_next_track_Down(object sender, MouseButtonEventArgs e)
        {
			e.Handled = true;
            b_next_track.Visibility = System.Windows.Visibility.Hidden;
            b_next_track_over.Visibility = System.Windows.Visibility.Hidden;
            b_next_track_click.Visibility = System.Windows.Visibility.Visible;
        }
        private void b_next_track_Down1(object sender, MouseButtonEventArgs e)
        {
            b_next_track.Visibility = System.Windows.Visibility.Hidden;
            b_next_track_over.Visibility = System.Windows.Visibility.Hidden;
            b_next_track_click.Visibility = System.Windows.Visibility.Visible;
        }
        private void b_next_track_Click(object sender, MouseButtonEventArgs e)
        {
            b_next_track.Visibility = System.Windows.Visibility.Visible;
            b_next_track_over.Visibility = System.Windows.Visibility.Hidden;
            b_next_track_click.Visibility = System.Windows.Visibility.Hidden;
        }

        private void MenuButton_Checked(object sender, RoutedEventArgs e)
        {
            ContextMenu cm = new ContextMenu();

            MenuItem mi_open = new MenuItem();
            mi_open.Header = "Открыть";
            MenuItem smi_open1 = new MenuItem();
            smi_open1.Header = "Открыть файл";
            MenuItem smi_open2 = new MenuItem();
            smi_open2.Header = "Открыть плэйлист";
            mi_open.Items.Add(smi_open1);
            mi_open.Items.Add(smi_open2);
            MenuItem mi_exit = new MenuItem();
            mi_exit.Header = "Выход";
            Separator s = new Separator();

            cm.Items.Add(mi_open);
            cm.Items.Add(s);
            cm.Items.Add(mi_exit);

            mi_exit.Click += new RoutedEventHandler(mi_exit_Click);

            ContextMenuService.SetPlacementTarget(cm, MenuButton);
            cm.Placement = PlacementMode.Bottom;
            cm.IsOpen = true;

            cm.Closed += new RoutedEventHandler(cm_Closed);

            var dlgItem = new MenuItem();
            dlgItem.Header = "Диалог";

            var item = new MenuItem();
            item.Header = "Вывод результатов";
            item.Click += new RoutedEventHandler(mi_output_dlg_action);
            dlgItem.Items.Add(item);

            item = new MenuItem();
            item.Header = "Справка";
            item.Click += new RoutedEventHandler(mi_help_dlg_action);
            dlgItem.Items.Add(item);

            item = new MenuItem();
            item.Header = "Настройки";
            item.Click += new RoutedEventHandler(mi_settings_dlg_action);
            dlgItem.Items.Add(item);

            item = new MenuItem();
            item.Header = "Анализ";
            item.Click += new RoutedEventHandler(mi_analysis_dlg_action);
            dlgItem.Items.Add(item);

			item = new MenuItem();
            item.Header = "Редактор тегов";
            item.Click += new RoutedEventHandler(mi_tags_dlg_action);
            dlgItem.Items.Add(item);
			
            cm.Items.Add(dlgItem);
        }

        private void mi_output_dlg_action(object sender, RoutedEventArgs e)
        {
            OutputDataDialog dialog = new OutputDataDialog("Заголовок окна", "Информация для пользователя");
            dialog.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            dialog.ShowDialog();

        }

        private void mi_settings_dlg_action(object sender, RoutedEventArgs e)
        {
            SettingsDialog dialog = new SettingsDialog();
            dialog.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            dialog.ShowDialog();
        }

        private void mi_help_dlg_action(object sender, RoutedEventArgs e)
        {
            string strUri = @"pack://application:,,,/MediaPlayerSatVer;component/Images/help_dialog.png";
            HelpWin dialog = new HelpWin("Справка", "информация для пользователей", new BitmapImage(new Uri(strUri)));
            dialog.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            dialog.ShowDialog();
        }

        private void mi_analysis_dlg_action(object sender, RoutedEventArgs e)
        {
            string strUri = @"pack://application:,,,/MediaPlayerSatVer;component/Images/default_dialog_image.jpg";
			AnalysisDialog dialog = new AnalysisDialog("Заголовок окна", "Текстовая информация.", new BitmapImage(new Uri(strUri)));
            //устанавливаем по центру экрана
            dialog.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            //запускаем модально
            dialog.ShowDialog();
        }
		
		private void mi_tags_dlg_action(object sender, RoutedEventArgs e)
        {
            TagEditDialog dialog = new TagEditDialog();
            dialog.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            dialog.ShowDialog();
        }

        private void mi_exit_Click(object sender, RoutedEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

        private void cm_Closed(object sender, RoutedEventArgs e)
        {
            MenuButton.IsChecked = false;
        }

        // <- Tabs methods
        private void tab_mouseMoveEvent(object sender, MouseEventArgs e)
        {
            var btn = (TextBlock)sender;
            btn.Opacity = 0.7;
        }
        private void tab_mouseLeaveEvent(object sender, MouseEventArgs e)
        {
            var btn = (TextBlock)sender;
            btn.Opacity = 1;
        }
        private void tab_mouseDownEvent(object sender, MouseButtonEventArgs e)
        {
            var btn = (TextBlock)sender;
            int index = Array.IndexOf(titles, btn.Text);
            if (index != cur_btn_index && cur_tab != null)
                makeLight(cur_tab);
            makeDark(btn);
            cur_tab = btn;
            cur_btn_index = index;
        }
        private void arrowRightClickEvent(object sender, MouseButtonEventArgs e)
        {
            var btn = (Image)sender;
            int index = Array.IndexOf(titles, tab3.Text);
            if (index < titles.Length - 1)
            {
                tab1.Text = titles[index - 1];
                tab2.Text = titles[index];
                tab3.Text = titles[index + 1];
                if (cur_btn_index == index + 1) { makeDark(tab3); cur_tab = tab3; }
                if (cur_btn_index == index) { makeDark(tab2); makeLight(tab3); cur_tab = tab2; }
                if (cur_btn_index == index - 1) { makeDark(tab1); makeLight(tab2); cur_tab = tab1; }
                if (cur_btn_index == index - 2) { makeLight(tab1); cur_tab = null; }
            }
        }
        private void arrowLeftClickEvent(object sender, MouseButtonEventArgs e)
        {
            var btn = (Image)sender;
            int index = Array.IndexOf(titles, tab1.Text);
            if (index > 0)
            {
                tab1.Text = titles[index - 1];
                tab2.Text = titles[index];
                tab3.Text = titles[index + 1];
                if (cur_btn_index == index + 2) { makeLight(tab3); cur_tab = null; }
                if (cur_btn_index == index + 1) { makeDark(tab3); makeLight(tab2); cur_tab = tab3; }
                if (cur_btn_index == index) { makeDark(tab2); makeLight(tab1); cur_tab = tab2; }
                if (cur_btn_index == index - 1) { makeDark(tab1); cur_tab = tab1; }
            }
        }
        private void makeLight(TextBlock tb)
        {
            BitmapImage img = new BitmapImage();
            img.BeginInit();
            img.UriSource = new Uri(@"pack://application:,,,/MediaPlayerSatVer;component/Images/tab_light.png");
            img.EndInit();
            ImageBrush brush = new ImageBrush();
            brush.ImageSource = img;
            tb.Background = brush;
        }
        private void makeDark(TextBlock tb)
        {
            BitmapImage img = new BitmapImage();
            img.BeginInit();
            img.UriSource = new Uri(@"pack://application:,,,/MediaPlayerSatVer;component/Images/tab_dark.png");
            img.EndInit();
            ImageBrush brush = new ImageBrush();
            brush.ImageSource = img;
            tb.Background = brush;
        }
        // Tabs methods ->

        private void searchText_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (searchText.Text == "Поиск")
            {
                searchText.Text = "";
                searchText.FontWeight = FontWeights.Normal;
                searchText.FontStyle = FontStyles.Normal;
            }
        }

        private void searchText_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (searchText.Text == "")
            {
                searchText.Text = "Поиск";
                searchText.FontWeight = FontWeights.Light;
                searchText.FontStyle = FontStyles.Oblique;
            }
        }

        private void search_Click(object sender, RoutedEventArgs e)
        {

        }
		
		
		private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			this.DragMove();
		}
		
		private void DenyMouseDown(object sender, MouseEventArgs e)
        {
            e.Handled = true;
        }
    }


    public class SongInfo
    {
        public Image PlayImage { get; set; }
        public string Time { get; set; }
        public string Title { get; set; }
        public int Number { get; set; }
        public string ToolTip { get; set; }
    }
}
